<template>
  <div class="createPost-container">
    <el-form ref="postForm" :model="postForm" :rules="rules" class="form-container">

      <sticky :z-index="10" :class-name="'sub-navbar '+postForm.status">
        <el-button v-loading="loading" style="margin-left: 10px;" type="success" @click="submitForm">
          {{ isEdit?'更新':'发布' }}
        </el-button>
      </sticky>

      <el-row>
        <el-col :span="19">
          <div class="createPost-main-container">

            <el-form-item style="margin-bottom: 40px;" prop="name">
              <MDinput v-model="postForm.name" required style="width:100%">
                产品名称
              </MDinput>
            </el-form-item>

            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item style="margin-bottom: 40px;" prop="categoryId" label="类别">
                  <category-selected v-model="postForm.categoryId" :list="categories" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item style="margin-bottom: 40px;" prop="suppliergid" label="提供商">
                  <Service v-model="postForm.suppliergid" :list="services" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item style="margin-bottom: 40px;" label="检索关键字">
                  <el-select
                    v-model="postForm.tags"
                    multiple
                    filterable
                    allow-create
                    default-first-option
                    remote
                    reserve-keyword
                    placeholder="请输入tag关键词"
                    :remote-method="remoteTags"
                  >
                    <el-option
                      v-for="item in tagList"
                      :key="item"
                      :label="item"
                      :value="item"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item prop="detail" style="margin-bottom: 30px;">
              <Tinymce ref="editor" v-model="postForm.detail" :height="400" width="100%" />
            </el-form-item>

            <el-form-item style="margin-bottom: 30px;" label-width="75px" label="商品简述:">
              <el-input v-model="postForm.profile" :rows="1" type="textarea" class="article-textarea" autosize placeholder="请输入商品简述" />
            </el-form-item>

            <el-form-item prop="images" style="margin-bottom: 30px;" label-width="100px" label="商品轮播图:">
              <Upload v-model="postForm.images" remote-path="upload/{filemd5}{.suffix}" margin="10px 20px 20px" :multiple="true" />
            </el-form-item>

            <el-form-item prop="waremodels" style="margin-bottom: 30px;" label="规格设定:" label-width="85px">
              <Standard v-model="postForm.waremodels" />
            </el-form-item>

            <el-form-item style="margin-bottom: 30px;" label="商品服务:" label-width="75px">
              <good-service v-model="postForm.server" />
            </el-form-item>

          </div>
        </el-col>

        <el-col :span="5" class="siderbar">
          <el-form-item style="margin-bottom: 40px;" prop="faceImg">
            <SingleImage1 v-model="postForm.faceImg" />
          </el-form-item>
        </el-col>
      </el-row>

    </el-form>
  </div>
</template>

<script>
import Tinymce from '@/components/Tinymce'
import Upload from '@/components/Upload/SingleImage'
import MDinput from '@/components/MDinput'
import Sticky from '@/components/Sticky' // 粘性header组件
import Standard from './Standard'
import GoodService from './GoodService'
import CategorySelected from './Sidebar/CategorySelected'
import Service from './Sidebar/Service'
import SingleImage1 from '@/components/Upload/SingleImage1'
import { searchUser } from '@/api/remote-search'

import { getWareInfo, saveWare } from '@/api/goods'

import { getTags } from '@/api/tag'

import { getCategory } from '@/api/catetory'

import { renderTime, getCascader } from '@/utils/util'

import { getSupplier } from '@/api/supplier'

export default {
  name: 'ArticleDetail',
  components: { Tinymce, MDinput, Upload, Sticky, Standard, GoodService, CategorySelected, Service, SingleImage1 },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    const validateRequire = (rule, value, callback) => {
      if (value === '') {
        this.$message({
          message: rule.field + '为必填项',
          type: 'error'
        })
        callback(new Error(rule.field + '为必填项'))
      } else {
        callback()
      }
    }
    return {
      gid: '',
      postForm: {
        name: '',
        detail: '',
        profile: '', // 简述
        images: '', // 轮播
        waremodels: undefined, // 规格
        server: '',
        categoryId: '',
        suppliergid: '',
        tags: [],
        faceImg: '' // S
      },
      loading: false,
      userListOptions: [],
      rules: {
        images: [{ required: true, validator: validateRequire }],
        name: [{ required: true, validator: validateRequire }],
        detail: [{ required: true, validator: validateRequire }],
        categoryId: [{ required: true, message: '请选择分类', trigger: 'change' }],
        suppliergid: [{ required: true, message: '请选择供货商', trigger: 'change' }],
        waremodels: [{ required: true, message: '请至少填写一个规格', trigger: 'change' }]
      },
      tempRoute: {},
      // 右边数据
      categories: [],
      services: [],
      shopName: ['1', '2'],
      tagList: []
    }
  },
  watch: {
    'postForm.server'(value) {
      console.log('选择的服务', value)
    },
    'postForm.categoryId'(value) {
      console.log('传回的分类gid', value)
    },
    'postForm.images'(value) {
      console.log('传回来的图片', value)
    },
    'postForm.waremodels'(value) {
      console.log('传回的产品规格', value)
    },
    tagList(newValue) {
      console.log(newValue)
    }
  },
  created() {
    if (this.isEdit) {
      this.gid = this.$route.query && this.$route.query.gid
      this.getWareInfo(this.gid)
    }
    this.getCategory()
    this.getSupplier()
    // Why need to make a copy of this.$route here?
    // Because if you enter this page and quickly switch tag, may be in the execution of the setTagsViewTitle function, this.$route is no longer pointing to the current page
    // https://github.com/PanJiaChen/vue-element-admin/issues/1221
    this.tempRoute = Object.assign({}, this.$route)
  },
  methods: {
    renderTime,
    getCascader,
    remoteTags(keyword) {
      this.getTags({ keyword })
    },
    getWareInfo(gid) {
      getWareInfo({ gid: gid }).then(res => {
        this.postForm.name = res.result.name
        this.postForm.detail = res.result.detail
        this.postForm.profile = res.result.profile
        this.postForm.images = res.result.images
        this.postForm.waremodels = res.result.waremodels
        this.postForm.server = res.result.server
        this.postForm.categoryId = res.result.categoryId
        this.postForm.suppliergid = res.result.suppliergid
        this.postForm.tags = res.result.tags && res.result.tags.length > 0 ? res.result.tags.split(',') : []
        this.postForm.faceImg = res.result.faceImg
      })
    },
    /**
     * 获取所有标签
     */
    getTags(data) {
      getTags(data).then(res => {
        this.tagList = res.result.list
      })
    },
    /**
     * 获取所有分类
     */
    getCategory() {
      getCategory().then(res => {
        if (res.result.length > 0) {
          // 将分类递归处理
          this.categories = this.getCascader(res.result)
        }
      })
    },
    /**
     * 获取所有服务商
     */
    getSupplier() {
      getSupplier().then(res => {
        console.log(res.result.list)
        if (res.result.list.length > 0) {
          // 循环原来数组返回一个新数组
          this.services = res.result.list.map((item) => { return { label: item.name, value: item.gid } })
        }
      })
    },
    submitForm() {
      this.$refs.postForm.validate(valid => {
        if (this.postForm.waremodels.find(item => item.name === '')) {
          this.$message({
            type: 'error',
            message: '规格名称不能为空~'
          })
          return
        }
        if (this.postForm.waremodels.find(item => item.stock === 0)) {
          this.$message({
            type: 'error',
            message: '库存不能为空~'
          })
          return
        }
        if (valid) {
          this.loading = true
          const newPostForm = {
            gid: this.gid,
            name: this.postForm.name,
            detail: this.postForm.detail,
            profile: this.postForm.profile, // 简述
            images: this.postForm.images, // 轮播
            waremodels: JSON.stringify(this.postForm.waremodels), // 规格
            server: this.postForm.server,
            categoryId: this.postForm.categoryId,
            suppliergid: this.postForm.suppliergid,
            tags: this.postForm.tags.toString(),
            faceImg: this.postForm.faceImg // S
          }
          saveWare(newPostForm).then(res => {
            const message = this.isEdit ? '商品更新成功' : '商品发布成功'
            this.$notify({
              title: '成功',
              message: message,
              type: 'success',
              duration: 2000
            })
          })
          this.postForm.status = 'published'
          this.loading = false
        } else {
          return false
        }
      })
    },
    getRemoteUserList(query) {
      searchUser(query).then(response => {
        if (!response.data.items) return
        this.userListOptions = response.data.items.map(v => v.name)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
  @import "~@/styles/mixin.scss";
  @import '@/assets/scss/mixin.scss';
  .createPost-container {
    position: relative;
    .createPost-main-container {
      margin: 20px 40px;
      .postInfo-container {
        position: relative;
        @include clearfix;
        margin-bottom: 10px;

        .postInfo-container-item {
          float: left;
        }
      }
    }

    .word-counter {
      width: 40px;
      position: absolute;
      right: 10px;
      top: 0px;
    }
  }
  .article-textarea {
    textarea {
      padding-right: 40px;
      resize: none;
      border: none;
      border-radius: 0px;
      border-bottom: 1px solid #bfcbd9;
    }
  }
  .siderbar{
    padding: 50px 40px 50px 0;
  }
  .el-collapse{
    border: 1px solid $bc3;
    margin-top: 40px;
   .el-collapse-item__wrap,.el-collapse-item__header {
      padding: 0 15px;
      border-color: $bc3;
    }
   .el-collapse-item__content{
      padding: 20px 0 20px;
    }
  }
  .el-card{
     box-shadow:none;
     border:none;
    .el-card__body{
      padding:0 20px 0 0;
    }
  }

</style>
